package com.leyou.item.service.iml;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.ParamService;
import com.leyou.item.service.SpecGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
    @Autowired
    private ParamService paramService;

    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        //方法一
        List<SpecGroupDTO> specGroupDTOS = query()
                .eq("category_id", id)
                .list()
                .stream()
                .map(SpecGroupDTO::new)
                .collect(Collectors.toList());
        //方法二
        // List<SpecGroupDTO> category_id1 = SpecGroupDTO.convertEntityList(query().eq("category_id", id).list());
        return specGroupDTOS;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long cid) {

        List<SpecGroupDTO> specGroupDTOS = this.queryGroupByCategory(cid);

        //根据分类id查询对应的规格参数
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(this.paramService.query().eq("category_id", cid).list());

        //对查询到的规格参数根据规格参数组id进行分组，key规格参数组的id，value为当前参数对应的集合
        Map<Long, List<SpecParamDTO>> paramDTOMap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        specGroupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(paramDTOMap.get(specGroupDTO.getId()));
        });

        return specGroupDTOS;
    }
    }

